package com.hn658.base.message.frontend.action.send.impl;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.hn658.base.message.frontend.action.send.IDeviceTokenActionImpl;
import com.hn658.base.message.frontend.action.send.vo.DeviceTokenRequest;
import com.hn658.base.message.frontend.action.send.vo.DeviceTokenResponse;
import com.hn658.base.message.notisender.exception.NotiSenderException;
import com.hn658.base.message.notisender.utils.IDeviceTokenManager;
import com.hn658.framework.common.AbstractBaseService;
import com.hn658.framework.common.IServiceResponse;

/**
 * 保存用户离线推送方式servlet
 * IOS apnsToken
 * android channelId
 */
@Controller("deviceTokenAction")
@Path("device")
@Produces("application/json; charset=UTF-8")
@Consumes("application/json; charset=UTF-8")
public class DeviceTokenActionImpl extends AbstractBaseService  implements IDeviceTokenActionImpl{

	@Autowired
	private IDeviceTokenManager deviceTokenManager;
	
	@Override
	@Path("deviceToken")
	@POST
	public IServiceResponse deviceToken(DeviceTokenRequest request){
		DeviceTokenResponse response = new DeviceTokenResponse();
		try {
			if(StringUtils.isNotBlank(request.getApnsToken())){
				deviceTokenManager.removeChannelId(request.getAppId(), request.getUid());
				deviceTokenManager.setApnsToken(request.getAppId(), request.getUid(), request.getApnsToken());
			}
			if(StringUtils.isNotBlank(request.getChannelId())&&StringUtils.isNotBlank(request.getUserId())){
				deviceTokenManager.removeApnsToken(request.getAppId(), request.getUid());
				deviceTokenManager.setChannelId(request.getAppId(), request.getUid(), Long.parseLong(request.getChannelId()), request.getUserId());
			}
			this.success(response);
		} catch (NotiSenderException e) {
			this.error(response, e);
		}
		return response;	
	}
}
